package net.csdn.business.common.oauth2.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.csdn.business.common.oauth2.mapper.PersonalAccessTokenMapper;
import net.csdn.business.common.domain.request.oauth.PersonalAccessTokenDTO;
import net.csdn.business.common.oauth2.model.entity.PersonalAccessToken;
import net.csdn.business.common.domain.request.oauth.PersonalAccessTokenQuery;
import net.csdn.business.common.domain.vo.oauth.PersonalAccessTokenVO;
import net.csdn.business.common.oauth2.service.IPersonalAccessTokenService;
import net.csdn.business.common.service.SnowflakeService;
import net.csdn.business.common.utils.UserInfoParser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * personalToken信息表;(person_token)表服务实现类
 * @author : duweiwei
 * @date : 2022-12-12
 */
@Service
public class PersonalAccessTokenServiceImpl extends ServiceImpl<PersonalAccessTokenMapper,PersonalAccessToken> implements IPersonalAccessTokenService {
    @Autowired
    private PersonalAccessTokenMapper personalAccessTokenMapper;

    @Autowired
    private SnowflakeService snowflakeService;

    /** 
     * 通过ID查询单条数据 
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public PersonalAccessTokenVO queryById(String id){
        LambdaQueryWrapper<PersonalAccessToken> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(PersonalAccessToken::getObjectId,id);
        PersonalAccessToken token = super.getOne(queryWrapper);
        if(token ==  null){
            return null;
        }
        PersonalAccessTokenVO tokenVO = new PersonalAccessTokenVO();
        BeanUtils.copyProperties(token,tokenVO);
        return tokenVO;
    }

    @Override
    public Page<PersonalAccessTokenVO> findPageList(PersonalAccessTokenQuery query) {
        //获得Page对象
        Page<PersonalAccessTokenVO> page = query.getPage();
        List<PersonalAccessTokenVO> pageList=baseMapper.findPageList(page,query);
        page.setRecords(pageList);
        return page;
    }

    @Override
    public List<PersonalAccessTokenVO> findList(PersonalAccessTokenQuery query) {
        return baseMapper.findList(query);
    }



     @Override
     public PersonalAccessTokenVO insertPersonTokenAndPermission(PersonalAccessTokenDTO addDto) {
         PersonalAccessToken personalAccessToken = new PersonalAccessToken();
         BeanUtils.copyProperties(addDto, personalAccessToken);
         personalAccessToken.setId(null);
         personalAccessToken.setObjectId(snowflakeService.nextNo());
         personalAccessToken.setUserId(addDto.getUserId());
         String tokenId =null;
         PersonalAccessToken perToken=null;
         do{
             StringBuilder atpToken=new StringBuilder("atp_");
             tokenId= atpToken.append(RandomUtil.randomString(32)).toString();
             //验证当前clientId是否存在，防止生成重复
             LambdaQueryWrapper<PersonalAccessToken> queryWrapper = new QueryWrapper<PersonalAccessToken>().lambda();
             queryWrapper.eq(PersonalAccessToken::getTokenId, tokenId);
             queryWrapper.eq(PersonalAccessToken::getRevoked,0);
             queryWrapper.eq(PersonalAccessToken::getIsDelete,0);
             perToken=baseMapper.selectOne(queryWrapper);
         }while (perToken!=null);
         personalAccessToken.setTokenId(tokenId);
         personalAccessToken.setRevoked(0);
         personalAccessToken.setIsDelete(0);
         personalAccessToken.setCreatedDate(new Date());
         //存储token信息
         personalAccessTokenMapper.insert(personalAccessToken);
         PersonalAccessTokenVO tokenVO = new PersonalAccessTokenVO();
         BeanUtils.copyProperties(personalAccessToken,tokenVO);
         return tokenVO;
     }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int revoked(String tokenId) {
        LambdaUpdateWrapper<PersonalAccessToken> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PersonalAccessToken::getTokenId,tokenId);
        updateWrapper.eq(PersonalAccessToken::getRevoked,0);
        updateWrapper.set(PersonalAccessToken::getRevoked,1);
        return baseMapper.update(null,updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int revokedAll(String userId) {
        LambdaUpdateWrapper<PersonalAccessToken> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PersonalAccessToken::getUserId,userId);
        updateWrapper.eq(PersonalAccessToken::getRevoked,0);
        updateWrapper.set(PersonalAccessToken::getRevoked,1);
        return baseMapper.update(null,updateWrapper);
    }

}